package com.thirteenClassicsServer.controller;

import com.thirteenClassics.dto.PictureCatalogQueryDTO;
import com.thirteenClassics.dto.jdbBookDto;
import com.thirteenClassics.entity.Book;
import com.thirteenClassics.result.Result;
import com.thirteenClassicsServer.mapper.*;
import com.thirteenClassicsServer.service.IBookService;
import com.thirteenClassicsServer.service.ICatalogBookService;
import com.thirteenClassicsServer.service.IPictureService;
import com.thirteenClassicsServer.service.impl.FileServiceImpl;
import com.thirteenClassicsServer.service.impl.XmlParseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/test")
// todo 1、优化代码 2、优化for里边操作数据库 3、缓存时间指定
public class TestController {
    private final Document document = null;
    @Resource
    private CatalogBookMapper catalogBookMapper;
    @Resource
    private CatalogMapper catalogMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private SentenceMapper sentenceMapper;
    @Resource
    private SentenceJdbMapper sentenceJdbMapper;
    @Resource
    private IBookService bookService;
    @Resource
    private IPictureService pictureService;
    @Resource
    private ICatalogBookService catalogBookService;
    @Resource
    private FileServiceImpl fileService;
    @Resource
    private XmlParseService xmlParseService;

    @CachePut(value = "value", key = "#a")
    @Async
    public Integer flashCache(int a) {
        try {
            Thread.sleep(5000);
            System.out.println("等待了5s ~~~");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return a * a * a;
    }


    //    public void flashCache(int a){
    //        flashCacheMethod((a));
    //    }


    public String cleanString(String s) {
        return s.trim().replaceAll("\\r\\n|\\r|\\n", "");
    }

    @Transactional
    public Long save(jdbBookDto bookDto) throws Exception {

        Book book = new Book();
        BeanUtils.copyProperties(bookDto, book);

        Long id = bookService.saveBookJdb(book);
        //新增书目的时候生成该书目所有目录信息表
        System.out.println(id);

        PictureCatalogQueryDTO pictureCatalogQueryDTO = new PictureCatalogQueryDTO();
        pictureCatalogQueryDTO.setBookName(book.getBookName());
        pictureCatalogQueryDTO.setBookId(book.getId());
        catalogBookService.insertcatalogJdb(pictureCatalogQueryDTO);


        //        XmlParseDTO xmlParseDTO = new XmlParseDTO();
        //        xmlParseDTO.setBookId(book.getId());
        //        xmlParseDTO.setPath(book.getDocPathReal());
        //        xmlParseDTO.setBookName(book.getBookName());
        //
        //
        //        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //        DocumentBuilder builder = factory.newDocumentBuilder();
        //        document = builder.parse(xmlParseDTO.getPath());
        //        NodeList juanmingList = document.getElementsByTagName("volume");
        //
        //        for (int i = 0; i < juanmingList.getLength(); i++) {
        //            Element juanmingElement = (Element) juanmingList.item(i);
        //            String juanmingText = juanmingElement.getTextContent().replace('，',',');
        //
        //            juanmingText = juanmingText + ',';
        //            System.out.println("volume: " + juanmingText);
        //
        //            // 查询卷名对应的目录ID
        //            Long catalogId = catalogMapper.selectCatalogIdByBookName(juanmingText);
        //            if(catalogId==null){
        //                throw new BaseException("xml文件格式错误，目录查不到");
        //            }
        //            // 设置卷名和目录ID
        //            BookIdAndCatalogDTO bookIdAndCatalogDTO = new BookIdAndCatalogDTO();
        //            bookIdAndCatalogDTO.setBookId(xmlParseDTO.getBookId());
        //            bookIdAndCatalogDTO.setCatalogId(catalogId);
        //
        //            // 查询卷名对应的入口ID
        //            Long entryId = catalogBookMapper.selectEntryIdByBookIdAndCatalogId(bookIdAndCatalogDTO);
        //
        //            // 初始化段落内容
        //            String jdContent = "";
        //
        //            // 获取下一个兄弟节点
        //            Node nextSibling = juanmingElement.getNextSibling();
        //
        //            // 遍历段落节点
        //            int p = 0;
        //            int s = 0;
        //            while (nextSibling != null) {
        //                // 判断当前节点是否为段落节点
        //                if(nextSibling.getNodeName().equals("volume"))break;
        //                if (nextSibling.getNodeName().equals("paragraph")) {
        //                    p++;
        //                    System.out.println("------------------------------段落分隔------------------------------");
        //
        //                    // 将下一个兄弟节点转换为元素节点
        //                    Element paragraphElement = (Element) nextSibling;
        //
        //                    // 获取段落下的每个句子
        //                    NodeList sList = paragraphElement.getElementsByTagName("s");
        //                    for (int k = 0; k < sList.getLength(); k++) {
        //                        Element sElement = (Element) sList.item(k);
        //                        String sText = sElement.getTextContent();
        //                        sText=cleanString(sText);
        //
        //                        jdContent = jdContent + sText + "\n";
        //
        //                        s++;
        //
        //                        // 插入句子数据
        //                        InsertSentenceJdbDTO insertSentenceJdbDTO = new InsertSentenceJdbDTO();
        //                        insertSentenceJdbDTO.setSentence(sText);
        //                        insertSentenceJdbDTO.setSentenceIds(Long.valueOf(s));
        //                        insertSentenceJdbDTO.setEntryId(entryId);
        //                        insertSentenceJdbDTO.setParagraphIds(Long.valueOf(p));
        //                        insertSentenceJdbDTO.setBookName(bookDto.getBookName());
        //
        //                        Sentence sentence = new Sentence();
        //                        BeanUtils.copyProperties(insertSentenceJdbDTO, sentence);
        //                        sentenceJdbMapper.insert(sentence);
        //
        //                        //System.out.println("s: " + sText);
        //                    }
        //                    jdContent=jdContent+"\n";
        //                }
        //
        //                // 获取下一个兄弟节点
        //                nextSibling = nextSibling.getNextSibling();
        //
        //
        //            }
        //
        //            // 更新段落内容
        //            CatalogBook catalogBook = new CatalogBook();
        //            catalogBook.setId(entryId);
        //            catalogBook.setJdContent(jdContent);
        //            catalogBookMapper.updatajdContent(catalogBook);
        //        }


        return id;
    }

    @GetMapping("/test")
    public Result test() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("论语");
        list.add("仪礼");
        list.add("周易");
        list.add("周礼");
        list.add("孝经");
        list.add("孟子");
        list.add("尔雅");
        list.add("尚书");
        list.add("春秋公羊传");
        list.add("春秋左传");
        list.add("春秋谷梁传");
        list.add("毛诗");
        list.add("礼记");
        list.add("四书");
        for (String s : list) {
            jdbBookDto bookDto = new jdbBookDto();
            bookDto.setBookName(s);
            bookDto.setJdbFlag(Long.valueOf(1));
            bookDto.setVersion("经典版");
            bookDto.setDocPathReal("./fileStorage/jdbFileStorage/" + s + ".xml");
            bookDto.setBookName(s);
            ArrayList<String> list1 = new ArrayList<>();
            list1.add("藏语(现代)");
            list1.add("藏语(古代)");
            list1.add("蒙古语(现代)");
            list1.add("蒙古语(古代)");
            list1.add("西夏文");
            list1.add("满文");
            bookDto.setBookLang(list1);
            Long id = save(bookDto);
            bookMapper.updateFlag(id);
        }
        return Result.success();
    }

    @GetMapping("/importBatchPics")
    public Result importBatchPics() {


        return Result.success();
    }
}